import torch
from torch.utils.data import Dataset
from torch.nn.utils.rnn import pad_sequence
import pickle, pandas as pd

# 定义MELDDataset类，继承自Dataset类
class MELDDataset(Dataset):
    # 初始化函数，传入路径和训练状态
    def __init__(self, path, train=True):
        # 从路径中加载数据
        path = f'E:/Multimodal_code/HTMM-ERC/data/meld_multimodal_features.pkl'
        self.videoIDs, self.videoSpeakers, self.videoLabels, self.videoText, \
        self.roberta2, self.roberta3, self.roberta4, \
        self.videoAudio, self.videoVisual, self.videoSentence, self.trainVid, \
        self.testVid, _ = pickle.load(open(path, 'rb'))

        # 根据训练状态，获取训练集或测试集
        self.keys = [x for x in (self.trainVid if train else self.testVid)]

        # 获取数据长度
        self.len = len(self.keys)

    # 获取指定索引的数据
    def __getitem__(self, index):
        # 获取指定索引的vid
        vid = self.keys[index]
        # 返回指定vid的数据
        return torch.FloatTensor(self.videoText[vid]), \
               torch.FloatTensor(self.videoVisual[vid]), \
               torch.FloatTensor(self.videoAudio[vid]), \
               torch.FloatTensor(self.videoSpeakers[vid]), \
               torch.FloatTensor([1] * len(self.videoLabels[vid])), \
               torch.LongTensor(self.videoLabels[vid]), \
               vid

    # 获取数据长度
    def __len__(self):
        return self.len

    # 返回标签
    def return_labels(self):
        return_label = []
        # 遍历keys，获取每个vid的标签
        for key in self.keys:
            return_label += self.videoLabels[key]
        # 返回标签
        return return_label

    # 定义collate_fn函数，用于拼接数据
    def collate_fn(self, data):
        # 将data转换为DataFrame
        dat = pd.DataFrame(data)
        # 返回拼接后的数据
        return [pad_sequence(dat[i]) if i < 4 else pad_sequence(dat[i], True) if i < 6 else dat[i].tolist() for i in
                dat]


